# coding: utf-8
__author__ = 'www.py3study.com'
import os
import time
import subprocess
import socket
class testing_server(object):
    def __init__(self):
        # 需要检测的域名,最后添加了一个不存在的域名,用来测试脚本的正确性,如有多个域名可往这个list里面添加
        self.domain_name_list = [\
            'www.py3study.com', \
            'py3study.com', \
            'm.py3study.com', \
            'g.cn', \
            'www.ragnarok233.com',\
            'www.guanzhizhao.com',\
            'zabbix.admin.com']
        self.ping_server_call()
        self.check_aliveness()

    def ping_server_call(self):
        fnull = open(os.devnull, 'w')
        for i in self.domain_name_list:
            domain_name = i
            #使用subprocess模块，用来过滤掉命令输出和返回信息
            result = subprocess.call('ping ' + domain_name + ' -n 3', shell=True, stdout=fnull, stderr=fnull)
            # result = subprocess.call('ping ' + domain_name + ' -n 3', shell=True)
            current_time = time.strftime('%Y%m%d-%H%M%S', time.localtime())
            testttttttt = "rrrrrrrrrrr"
            time.sleep(1)
            if result:
                print('时间: {} 域名 {} ping fail'.format(current_time, domain_name))
            else:
                print('时间: {} 域名 {} ping ok {}'.format(current_time, domain_name,testttttttt))
                # print('时间: {} 域名 {} ping ok {}'.format(current_time, domain_name,'testttttttt'))
        fnull.close()

    def check_aliveness(self):
        sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sk.settimeout(1)
        ip = '54.255.208.167' #ip对应redis服务器的ip地址
        port = 6379  #端口默认是6379，如果修改了redis的端口，这里也必须改
        try:
            sk.connect((ip, port))
            print('server:{} 端口:{} redis is OK !'.format(ip, port))
            return True
        except Exception:
            print('\n')
            print('\n')
            print('\n')
            print('你好')
            print('')
            print('')
            print('sever:{} 端口:{} redis is NOT OK !'.format(ip, port))
            return False
        finally:
            sk.close()

if __name__ == '__main__':
    st = testing_server()